<?php

declare(strict_types=1);

namespace app\middleware;

use app\service\factory\ResponseFactory;

class ClientMiddleware
{

    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // 获取请求头
        $clientMark = $request->header('X-Client-Mark');

        $deviceFingerprint = $request->header('X-Device-Fingerprint');

        // 验证 X-Device-Fingerprint 格式
        if (!(bool) preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i', $deviceFingerprint)) {
            return json(ResponseFactory::error('设备指纹格式不正确', 400));
        }

        // 记录客户端信息到请求对象中，供后续使用
        $request->client_mark = $clientMark;
        $request->device_fingerprint = $deviceFingerprint;

        // 验证通过，继续执行后续操作
        return $next($request);
    }
}
